import React, { Component } from 'react';
import styles from './style.scss';
import PropTypes from 'prop-types';
import { noop } from '@utils';

class Message extends Component {
    static propTypes = {
        wrapper: PropTypes.object.isRequired,
        content: PropTypes.string.isRequired,
        duration: PropTypes.number,
        type: PropTypes.string.isRequired,
        onClose: PropTypes.func
    };

    static defaultProps = {
        duration: 3,
        onClose: noop
    };

    componentDidMount() {
        this.clearCloseTimer();
        if (this.props.duration) {
            this.closeTimer = setTimeout(() => {
                this.close();
            }, this.props.duration * 1000);
        }
    }
    
    componentDidUpdate() {
        this.componentDidMount();
    }
    
    componentWillUnmount() {
        this.clearCloseTimer();
    }

    clearCloseTimer() {
        if (this.closeTimer) {
            clearTimeout(this.closeTimer);
            this.closeTimer = null;
        }
    }

    close() {
        document.body.removeChild(this.props.wrapper);
        this.clearCloseTimer();
        this.props.onClose();
    }

    render() {
        const { content, type } = this.props;
        let className = `${styles.icon}`;
        if (type === 'success') {
            className += ` ${styles.success}`;
        } else if (type === 'error') {
            className += ` ${styles.error}`;
        } else if (type === 'warning') {
            className += ` ${styles.warning}`;
        }
        return (
            <div className={styles.container}>
                <div className={styles.content}>
                    <i className={className}></i><span>{content}</span>
                </div>
            </div>
        );
    }
}

export default Message;